﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
using Nop.Core;
using Nop.Core.Domain.Cms;
using Nop.Plugin.Widgets.GoogleAnalytics.Components;
using Nop.Services.Cms;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Plugins;
using Nop.Web.Framework.Infrastructure;

namespace Nop.Plugin.Widgets.GoogleAnalytics;

/// <summary>
/// Google Analytics plugin
/// </summary>
public class GoogleAnalyticsPlugin : BasePlugin, IWidgetPlugin
{
    #region Fields

    protected readonly IActionContextAccessor _actionContextAccessor;
    protected readonly ILocalizationService _localizationService;
    protected readonly IWebHelper _webHelper;
    protected readonly ISettingService _settingService;
    protected readonly IUrlHelperFactory _urlHelperFactory;
    protected readonly WidgetSettings _widgetSettings;

    #endregion

    #region Ctor

    public GoogleAnalyticsPlugin(IActionContextAccessor actionContextAccessor,
        ILocalizationService localizationService,
        IWebHelper webHelper,
        ISettingService settingService,
        IUrlHelperFactory urlHelperFactory,
        WidgetSettings widgetSettings)
    {
        _actionContextAccessor = actionContextAccessor;
        _localizationService = localizationService;
        _webHelper = webHelper;
        _settingService = settingService;
        _urlHelperFactory = urlHelperFactory;
        _widgetSettings = widgetSettings;
    }

    #endregion

    #region Methods

    /// <summary>
    /// Gets widget zones where this widget should be rendered
    /// </summary>
    /// <returns>
    /// A task that represents the asynchronous operation
    /// The task result contains the widget zones
    /// </returns>
    public Task<IList<string>> GetWidgetZonesAsync()
    {
        return Task.FromResult<IList<string>>(new List<string>
        {
            PublicWidgetZones.HeadHtmlTag
        });
    }

    /// <summary>
    /// Gets a configuration page URL
    /// </summary>
    public override string GetConfigurationPageUrl()
    {
        return _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext).RouteUrl(GoogleAnalyticsDefaults.ConfigurationRouteName);
    }

    /// <summary>
    /// Gets a type of a view component for displaying widget
    /// </summary>
    /// <param name="widgetZone">Name of the widget zone</param>
    /// <returns>View component type</returns>
    public Type GetWidgetViewComponent(string widgetZone)
    {
        ArgumentNullException.ThrowIfNull(widgetZone);

        if (widgetZone.Equals(PublicWidgetZones.HeadHtmlTag))
            return typeof(WidgetsGoogleAnalyticsViewComponent);

        return null;
    }

    /// <summary>
    /// Install plugin
    /// </summary>
    /// <returns>A task that represents the asynchronous operation</returns>
    public override async Task InstallAsync()
    {
        var settings = new GoogleAnalyticsSettings
        {
            GoogleId = "G-XXXXXXXXXX",
            TrackingScript = @"<!-- Global site tag (gtag.js) - Google Analytics -->
                <script async src='https://www.googletagmanager.com/gtag/js?id={GOOGLEID}'></script>
                <script>
                  window.dataLayer = window.dataLayer || [];
                  function gtag(){dataLayer.push(arguments);}
                  gtag('js', new Date());

                  gtag('config', '{GOOGLEID}');
                  {CUSTOMER_TRACKING}
                </script>"
        };
        await _settingService.SaveSettingAsync(settings);

        if (!_widgetSettings.ActiveWidgetSystemNames.Contains(GoogleAnalyticsDefaults.SystemName))
        {
            _widgetSettings.ActiveWidgetSystemNames.Add(GoogleAnalyticsDefaults.SystemName);
            await _settingService.SaveSettingAsync(_widgetSettings);
        }

        await _localizationService.AddOrUpdateLocaleResourceAsync(new Dictionary<string, string>
        {
            ["Plugins.Widgets.GoogleAnalytics.UseSandbox"] = "UseSandbox",
            ["Plugins.Widgets.GoogleAnalytics.UseSandbox.Hint"] = "Determine whether to use the sandbox environment for testing purposes. This setting only applies to sending eCommerce information via the Measurement Protocol.",
            ["Plugins.Widgets.GoogleAnalytics.GoogleId"] = "ID",
            ["Plugins.Widgets.GoogleAnalytics.GoogleId.Hint"] = "Enter Google Analytics ID.",
            ["Plugins.Widgets.GoogleAnalytics.ApiSecret"] = "API Secret",
            ["Plugins.Widgets.GoogleAnalytics.ApiSecret.Hint"] = "Enter API Secret.",
            ["Plugins.Widgets.GoogleAnalytics.TrackingScript"] = "Tracking code",
            ["Plugins.Widgets.GoogleAnalytics.TrackingScript.Hint"] = "Paste the tracking code generated by Google Analytics here. {GOOGLEID} and {CUSTOMER_TRACKING} will be dynamically replaced.",
            ["Plugins.Widgets.GoogleAnalytics.EnableEcommerce"] = "Enable eCommerce",
            ["Plugins.Widgets.GoogleAnalytics.EnableEcommerce.Hint"] = "Check to pass information about orders to Google eCommerce feature.",
            ["Plugins.Widgets.GoogleAnalytics.IncludeCustomerId"] = "Include customer ID",
            ["Plugins.Widgets.GoogleAnalytics.IncludeCustomerId.Hint"] = "Check to include customer identifier to script.",
            ["Plugins.Widgets.GoogleAnalytics.IncludingTax"] = "Include tax",
            ["Plugins.Widgets.GoogleAnalytics.IncludingTax.Hint"] = "Check to include tax when generating tracking code for eCommerce part.",
            ["Plugins.Widgets.GoogleAnalytics.Instructions"] = "<p>Google Analytics is a free website stats tool from Google. It keeps track of statistics about the visitors and eCommerce conversion on your website.<br /><br />Follow the next steps to enable Google Analytics integration:<br /><ul><li><a href=\"http://www.google.com/analytics/\" target=\"_blank\">Create a Google Analytics account</a> and follow the wizard to add your website</li><li>Copy the <b>MEASUREMENT ID</b> into the <b>ID</b> box below</li><li>In Google Analytics click on the <b>Measurement Protocol API secrets</b> under <b>Events</b></li><li>Click on <b>Create</b> button and follow the instructions to create a new API secret</li><li>Copy the API secret into the <b>API Secret</b> box below</li><li>Click the 'Save' button below and Google Analytics will be integrated into your store</li></ul><br /></p>"
        });

        await base.InstallAsync();
    }

    /// <summary>
    /// Uninstall plugin
    /// </summary>
    /// <returns>A task that represents the asynchronous operation</returns>
    public override async Task UninstallAsync()
    {
        //settings
        if (_widgetSettings.ActiveWidgetSystemNames.Contains(GoogleAnalyticsDefaults.SystemName))
        {
            _widgetSettings.ActiveWidgetSystemNames.Remove(GoogleAnalyticsDefaults.SystemName);
            await _settingService.SaveSettingAsync(_widgetSettings);
        }
        await _settingService.DeleteSettingAsync<GoogleAnalyticsSettings>();

        //locales
        await _localizationService.DeleteLocaleResourcesAsync("Plugins.Widgets.GoogleAnalytics");

        await base.UninstallAsync();
    }

    #endregion

    #region Properties

    /// <summary>
    /// Gets a value indicating whether to hide this plugin on the widget list page in the admin area
    /// </summary>
    public bool HideInWidgetList => false;

    #endregion
}